#!/usr/bin/env lua

package.path = package.path .. ";/usr/share/lua/?.lua;../?.lua"
package.cpath = package.cpath .. ";/usr/lib/lua/?.so;../?.so"

Fixture = require('fit.Fixture')
Parse = require('fit.Parse')

-- Global Variables ------------------
output = ""
input = ""
fixture = {}

-- Functions -------------------------
local function args(argv)
    inFile = assert(io.open(argv[1], "r"))
    fixture = Fixture()

    fixture.summary["input file"] = argv[1]
    fixture.summary["output file"] = argv[2]

    input = inFile:read("*all")
    output = assert(io.open(argv[2], "w"))
end

local function process()
    if string.find(input, "<wiki>") ~= nil then
        tables = Parse(input, {"wiki", "table", "tr", "td"})
        fixture:doTables(tables.parts)
    else
        tables = Parse(input, {"table", "tr", "td"})
        fixture:doTables(tables)
    end

    tables:print(output)
end

local function finish()
    output:close()

    io.stderr:write(tostring(fixture.counts:string()) .. "\n")
    os.exit(fixture.counts.wrong + fixture.counts.exceptions)
end

local function run(argv)
    if #argv ~= 2 then
        print("incorrect parameters passed")
        return
    end
    args(argv)
    process()
    finish()
end

run(arg)
